/*
ctx：Canvas绘图环境
fromX, fromY：起点坐标（也可以换成p1，只不过它是一个数组）
toX, toY：终点坐标 (也可以换成p2，只不过它是一个数组)
theta：三角斜边一直线夹角
headlen：三角斜边长度
width：箭头线宽度
color：箭头颜色
isDash: 是否为虚线
*/
function drawArrow(ctx, fromX, fromY, toX, toY,theta,headlen,width,color,isDash)
{
    theta = typeof(theta) != 'undefined' ? theta : 30;
    headlen = typeof(theta) != 'undefined' ? headlen : 10;
    width = typeof(width) != 'undefined' ? width : 1;
    color = typeof(color) != 'color' ? color : '#000'; // 计算各角度和对应的P2,P3坐标
    var angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI, angle1 = (angle + theta) * Math.PI / 180, angle2 = (angle - theta) * Math.PI / 180, topX = headlen * Math.cos(angle1), topY = headlen * Math.sin(angle1), botX = headlen * Math.cos(angle2), botY = headlen * Math.sin(angle2);
    ctx.save();
    ctx.beginPath(); 
    var arrowX = fromX - topX, arrowY = fromY - topY; 
    //画横线
    if(isDash == true){
        ctx.setLineDash([20,20]);
    }
    ctx.moveTo(fromX, fromY);
    ctx.lineTo(toX, toY);
    ctx.strokeStyle = color; 
    ctx.lineWidth = width; 
    ctx.stroke(); 
    ctx.restore();
    //\画横线
    ctx.save();
    ctx.beginPath(); 
    arrowX = toX + topX; 
    arrowY = toY + topY; 
    ctx.moveTo(arrowX, arrowY);
    ctx.lineTo(toX, toY); 
    arrowX = toX + botX; 
    arrowY = toY + botY; 
    ctx.lineTo(arrowX, arrowY); 
    ctx.strokeStyle = color; 
    ctx.lineWidth = width; 
    ctx.stroke(); 
    ctx.restore(); 
}

/*
str:要绘制的字符串
canvas:canvas对象
initX:绘制字符串起始x坐标
initY:绘制字符串起始y坐标
lineHeight:字行高，自己定义个值即可
fontHeight:字体高度
verticalAlign:文字垂直对齐
*/
function canvasTextAutoLine(str,canvas,rectX,rectY,rectW,rectH,lineHeight,fontHeight,verticalAlign){
    lineHeight = typeof(lineHeight) != 'undefined' ? lineHeight : 20;
    fontHeight = typeof(fontHeight) != 'undefined' ? fontHeight : 20;
    verticalAlign = typeof(verticalAlign) != 'undefined' ? verticalAlign : 'middle';
    var lineWidth = 0;
    var lastSubStrIndex= 0;
    var rowTexts = [];
    for(var i=0;i<str.length;i++){ 
        if(i == str.length-1){
            rowTexts.push(str.substr(lastSubStrIndex));
        }else{
            lineWidth += canvas.measureText(str[i]).width;
            lineWidthNext = canvas.measureText(str[i + 1]).width;
            if(lineWidth + lineWidthNext > rectW){
                rowTexts.push(str.substr(lastSubStrIndex,i - lastSubStrIndex + 1));
                lineWidth=0;
                lastSubStrIndex=i+1;
            }
        }
    }
    var startY = rectY;
    if(verticalAlign == 'middle'){
        startY =  rectY + (rectH - rowTexts.length * lineHeight) / 2;
    }else if(verticalAlign == 'top'){
        startY = rectY;
    }else if(verticalAlign == 'bottom'){
        startY = rectY + rectH - rowTexts.length * lineHeight;
    }
    startY += lineHeight / 2;
    for(var i=0;i<rowTexts.length;i++){
        canvas.fillText(rowTexts[i],rectX,startY + i * lineHeight + fontHeight / 2);
    }
  }